#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include <unistd.h>
#include "MQTTClient.h"

char *address = "tcp://123.207.182.21:1883";
char *client_id = "publish_client";
char *topic = "test/linux";
char messageBuffer[1024];
const int timeOut = 10000;
const int QOS = 0;

int main(void) {
  int rc = 0;

  MQTTClient client;
  MQTTClient_connectOptions connectOptions = MQTTClient_connectOptions_initializer;
  MQTTClient_message publishMessage = MQTTClient_message_initializer;
  MQTTClient_deliveryToken token;

  connectOptions.keepAliveInterval = 60;
  connectOptions.cleansession = 1;

  MQTTClient_create(&client, address, client_id, MQTTCLIENT_PERSISTENCE_NONE, NULL);

  connectOptions.username = "gary";
  connectOptions.password = "827289014";

  printf("MQTT user is %s\n", connectOptions.username);
  printf("MQTT password is %s\n", connectOptions.password);
  printf("MQTT version code is %d\n", connectOptions.MQTTVersion);
  printf("MQTT returned.MQTTVersion is %d\n", connectOptions.returned.MQTTVersion);

  if(rc = MQTTClient_connect(client, &connectOptions) != MQTTCLIENT_SUCCESS) {
    printf("MQTTClient connect error code = %d\n", rc);
    printf("MQTTClient_connect failure:%s\n", strerror(errno));
    return -1;
  }

  publishMessage.qos = QOS;
  publishMessage.retained = 0;

  while(1) {
    printf("enter the message you want to send\n");
    fgets(messageBuffer, sizeof(messageBuffer), stdin);

    publishMessage.payload = (void*)messageBuffer;
    publishMessage.payloadlen = strlen(messageBuffer);

    MQTTClient_publishMessage(client,topic,&publishMessage,&token);
    rc = MQTTClient_waitForCompletion(client, token, timeOut);

    printf("Message with delivery token %d delivered\n",rc);
    printf("%s\n",messageBuffer);//用于测试
    sleep(3);
  }

  return 0;
}
